const random = (x, y) => Math.floor(Math.random() * (y - x + 1)) + x

export const hashcode = (len = 5) => {
  const code = '0123456789qazwsxedcrfvtgbyhnujmikolp'
  let hash = ''
  while (len--) {
    hash += code[random(0, 35)]
  }
  return hash
}

export const enCamelCase = val =>
  val.replace(/[-_][a-zA-Z]/g, m => m.replace(/[-_]/g, '').toUpperCase())

export const enUpperCamelCase = val =>
  val ? enCamelCase(val.replace(/^[a-zA-Z]/, m => m.toUpperCase())) : ''

export const deCamelCase = val =>
  val.replace(/([A-Z])/g, (match, _, index) => {
    const lowerCase = match.toLowerCase()
    return index ? '-' + lowerCase : lowerCase
  })

export const ObjectKeys = Object.keys

const handleCopyVal = val => {
  if (val) return val
  if (val === null || val === 0 || val === '' || val === false) return val
  if (typeof val === 'undefined') return ''
  if (typeof val === 'object') return ObjectCopy(val)
  console.error(val, '未处理值返回""')
  return ''
}
// 针对object深复制, 注意没有考虑array
// 以obj参数属性为准, 根据raw参数, 默认为undefined
// 有   则复制raw到obj并返回obj
// 没有 则复制obj到new object并返回object
export const ObjectCopy = (obj, raw, option) => {
  const inverse = typeof raw === 'undefined'
  const res = inverse ? {} : obj
  const { skip } = option || {}
  const each = key =>
    (skip && skip === key) ||
    (res[key] = handleCopyVal(inverse ? obj[key] : raw[key]))
  ObjectKeys(obj).forEach(each)
  return res
}

export const IsArray = Array.isArray
export const IsObject = val => val !== null && typeof val === 'object'
export const IsEmptyObj = val =>
  IsObject(val) ? !ObjectKeys(val).length : true
